package leetcode.code1209;

import java.util.Stack;

public class Solution {
	public String removeDuplicates(String s, int k) {
		Stack<int[]> stack = new Stack<>();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!stack.isEmpty() && stack.peek()[0] == c) {
				if (stack.peek()[1] + 1 == k) {
					stack.pop();
				} else {
					stack.peek()[1]++;
				}
			} else {
				stack.add(new int[] { c, 1 });
			}
		}
		StringBuffer ans = new StringBuffer();
		while(!stack.isEmpty()) {
			int[] cur = stack.pop();
			ans.append(String.valueOf((char)cur[0]).repeat(cur[1]));
		}
		ans.reverse();
		return ans.toString();
	}
}
